package com.yzf.demo.demo.DesignPattren.PrototypePattern.BeanUtil;

import java.lang.reflect.Field;

/**
 * Created by 于占峰 on 2020/3/16/016.
 * javaBeanUtil工具  利用反射机制实现拷贝
 */
public class JavaBeanUtils {

    public static Object clone(Object protoype) {
        //获得class
        Class clazz = protoype.getClass();
        Object returnBean = null;
        try {
            //反射机制创建实例
            returnBean = clazz.newInstance();
            //获得并迭代所有字段
            for (Field field : clazz.getDeclaredFields()) {
                //设置访问权限
                field.setAccessible(true);
                //复制拷贝
                field.set(returnBean, field.get(protoype));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnBean;
    }
}
